package com.qinglei.recoup.longconn.handler;

import com.qinglei.recoup.longconn.constant.LongConnConstant;
import com.qinglei.recoup.longconn.entity.Message;
import com.qinglei.recoup.longconn.utils.CRCUtils;
import com.qinglei.recoup.longconn.utils.CommonUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MessageEncoder extends MessageToByteEncoder<Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        try {
            ByteBuf buffer = Unpooled.buffer();
            buffer.writeBytes(CommonUtils.hexStringToBytes(msg.getHeader()));
            buffer.writeByte(msg.getProjectCode());
            buffer.writeBytes(CommonUtils.hexStringToBytes(msg.getFuncCode()));
            buffer.writeShort(msg.getNonce());
            buffer.writeByte(msg.getEncMode());
            buffer.writeBytes(CommonUtils.hexStringToBytes(msg.getSn()));
            buffer.writeBytes(CommonUtils.hexStringToBytes(msg.getPn()));
            byte[] body = msg.getBody().encode();
            buffer.writeShort(body.length + LongConnConstant.FIXED_FIELD_LENGTH);
            buffer.writeBytes(body);
            buffer.writeBytes(CommonUtils.hexStringToBytes(msg.getTail()));
            //校验数据
            byte[] crcBuf = new byte[buffer.readableBytes()];
            buffer.getBytes(0, crcBuf);
            int dataCrc = CRCUtils.getCRC16(crcBuf);
            buffer.writeShort(dataCrc);

            out.writeBytes(buffer);
            // 调试用
            byte[] sendMsg = new byte[buffer.writerIndex()];
            buffer.getBytes(0, sendMsg);
            log.info("encode message : " + CommonUtils.bytesToHexString(sendMsg));
        } catch (Exception e) {
            log.error("encode error:", e);
        }
    }
}
